package com.cloud.punish.tasklist.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cloud.punish.tasklist.entity.TaskList;
import com.cloud.punish.tasklist.entity.TaskListPart;
import com.cloud.punish.tasklist.mapper.TaskListMapper;
import com.cloud.punish.tasklist.mapper.TaskListPartMapper;
import com.cloud.punish.tasklist.service.TaskListPartService;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

@Service
@Transactional
public class TaskListPartServiceImpl implements TaskListPartService {

	@Autowired
	private TaskListPartMapper taskListPartMapper;

	@Autowired
	private TaskListMapper taskListMapper;

	@Override
	public Long saveUpdateTaskListPart(long procDefId, long taskListId, String partIds) {
		Example example = new Example(TaskListPart.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("procDefId", procDefId);
		criteria.andEqualTo("taskListId", taskListId);
		taskListPartMapper.deleteByExample(example);

		String[] parts = partIds.split(",");
		if (null != parts && parts.length > 0) {
			for (String p : parts) {
				if (!StringUtils.isEmpty(p)) {
					TaskListPart part = new TaskListPart();
					part.setPartId(Long.valueOf(p));
					part.setProcDefId(procDefId);
					part.setTaskListId(taskListId);
					taskListPartMapper.insert(part);
				}
			}
		}
		return taskListId;
	}

	@Override
	public List<TaskListPart> listByTaskListProcDef(long taskListId, long procDefId) {
		Example example = new Example(TaskListPart.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("procDefId", procDefId);
		criteria.andEqualTo("taskListId", taskListId);
		return taskListPartMapper.selectByExample(example);
	}

	@Override
	public List<TaskList> listTaskListByPart(Integer groupId, List<Long> parts) {
		List<TaskList> result = new ArrayList<TaskList>();
		Example example = new Example(TaskList.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("groupId", groupId);
		example.orderBy("displayOrder");
		List<TaskList> taskLists = taskListMapper.selectByExample(example);
		List<TaskListPart> listParts = taskListPartMapper.findTaskList(parts);
		for (TaskList taskList : taskLists) {
			for (TaskListPart part : listParts) {
				if (taskList.getTaskListId() == part.getTaskListId()) {
					result.add(taskList);
					break;
				}
			}
		}
		return result;
	}
}
